package com.example.smartall.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.smartall.R;
import com.example.smartall.adapter.NewsListAdapter;
import com.example.smartall.adapter.ServiceRecycleAdapter;
import com.example.smartall.api.Api;
import com.example.smartall.api.ApiConfig;
import com.example.smartall.api.NetCallBack;
import com.example.smartall.entity.HomeBannerBean;
import com.example.smartall.entity.NewsBean;
import com.example.smartall.entity.NewsTypeBean;
import com.example.smartall.entity.ServiceBean;
import com.example.smartall.fragment.base.BaseFragment;
import com.example.smartall.ui.HomeActivity;
import com.example.smartall.ui.HospitalActivity;
import com.example.smartall.ui.JobHuntingActivity;
import com.example.smartall.ui.OrderActivity;
import com.example.smartall.ui.PaymentActivity;
import com.example.smartall.ui.SearchResultActivity;
import com.example.smartall.ui.SubwayActivity;
import com.example.smartall.ui.base.BaseActivity;
import com.example.smartall.ui.CarParkingActivity;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 主页
 * <p>
 * bug1 Banner开源库在切换fragment后（此fragment销毁），数据源依旧存在
 * 在调用onCreate（）后获取的数据依旧加载到banner当中
 */
public class HomeFragment extends BaseFragment {

    private EditText etSearch;
    private Button btSearch;
    private Banner banner;
    private RecyclerView rvService;
    private TabLayout typeTab;
    private ListView lvNews;
    private BaseActivity activity;
    //banner的图片地址
    private List<String> urls = new ArrayList<>();
    //全部服务数据
    private List<ServiceBean.RowsBean> serviceBeans = new ArrayList<>();
    //服务recycle适配器
    private ServiceRecycleAdapter recycleAdapter;
    //新闻数分类据
    private List<NewsTypeBean.DataBean> dataBeans = new ArrayList<>();
    //新闻数据
    private List<NewsBean.RowsBean> newsBeans = new ArrayList<>();
    //新闻list适配器
    private NewsListAdapter newsListAdapter;
    //新闻分类id
    private final List<Integer> newsType = new ArrayList<>();

    private final MHandler handler = new MHandler();

    private Map<String, Class> serviceClickHandler;

    public HomeFragment(BaseActivity activity) {
        this.activity = activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_home, container, false);
        init(view);
        initEvent();
        //获取轮播图数据
        getBannerUrl();
        //获取服务图标数据
        getAllService();
        //获取新闻类型
        getNewsType();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (serviceClickHandler == null){
            serviceClickHandler = new HashMap<>();
            //填充 有的服务图标在主页上可能不显示的
            serviceClickHandler.put("城市地铁", SubwayActivity.class);
            serviceClickHandler.put("门诊预约", HospitalActivity.class);
            serviceClickHandler.put("停哪儿", CarParkingActivity.class);
            serviceClickHandler.put("外卖订餐", OrderActivity.class);
            serviceClickHandler.put("生活缴费", PaymentActivity.class);
            serviceClickHandler.put("找工作", JobHuntingActivity.class);
        }
        if (urls.size() > 0){
            handler.sendEmptyMessage(0x01);
        }
        if (serviceBeans.size() > 0){
            handler.sendEmptyMessage(0x02);
        }
        if (newsType.size() > 0){
            handler.sendEmptyMessage(0x03);
        }
        if (newsBeans.size() > 0){
            handler.sendEmptyMessage(0x04);
        }
    }

    private void init(View view) {
        etSearch = (EditText) view.findViewById(R.id.et_search);
        btSearch = (Button) view.findViewById(R.id.bt_search);
        banner = (Banner) view.findViewById(R.id.banner);
        rvService = (RecyclerView) view.findViewById(R.id.rv_service);
        typeTab = (TabLayout) view.findViewById(R.id.type_tab);
        lvNews = (ListView) view.findViewById(R.id.lv_news);
        //recycleView 服务 网格布局 4列
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 4);
        rvService.setLayoutManager(gridLayoutManager);
        //Tab 新闻分类 滑动布局
        typeTab.setTabMode(TabLayout.MODE_SCROLLABLE);
    }

    private void initEvent() {
        //搜索新闻功能 弹起键盘搜索监听
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    if ("".equals(etSearch.getText().toString())) return false;
                    toStartSearchResult();
                }
                return false;
            }
        });
        //搜索功能 按钮搜索
        btSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("".equals(etSearch.getText().toString())) return;
                toStartSearchResult();
            }
        });
        //新闻tab切换时加载对于类型新闻
        typeTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //若新闻分类数据为空 不加载
                if (newsType.size() == 0) return;
                getNews();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    //主页服务点击监听 若要求主页和服务两个界面同时有点击效果，应应用在adapter当中监听
    private void setRecycleViewEvent() {
        recycleAdapter.setListener(new ServiceRecycleAdapter.OnItemClickedListener() {
            @Override
            public void onClick(int position, String serviceName) {
                //根据位置
//                switch (position){
//                    case 1:
//                        break;
//                }
                //根据名称
//                switch (serviceName) {
//                    case "城市地铁":
//                        startActivity(new Intent(getActivity(), SubwayActivity.class));
//                        break;
//                }

                //新玩意 唯一美中不足的就是这个‘更多服务’了 否则一行代码足够 原写法参见上面
                if (serviceClickHandler.containsKey(serviceName)) {
                    migrateTo(serviceClickHandler.get(serviceName));
                } else {
                    ((HomeActivity) activity).vpHome.setCurrentItem(1);
                }
            }
        });
    }

    //新闻
    private void getNews() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("type", newsType.get(typeTab.getSelectedTabPosition()));
        Api.config(ApiConfig.NEWS_URL, params).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                NewsBean newsBean = new Gson().fromJson(res, NewsBean.class);
                if (newsBean != null) {
                    newsBeans = newsBean.getRows();
                    handler.sendEmptyMessage(0x04);
                }
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }

    //新闻类型
    private void getNewsType() {
        if (newsType.size() > 0) return;
        Api.config(ApiConfig.NEWS_TYPE_URL, null).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                NewsTypeBean newsTypeBean = new Gson().fromJson(res, NewsTypeBean.class);
                if (newsTypeBean != null && newsTypeBean.getCode() == 200) {
                    dataBeans = newsTypeBean.getData();
                    handler.sendEmptyMessage(0x03);
                }
            }

            @Override
            public void onFailure(Exception e) {
            }
        });
    }

    //服务图标
    private void getAllService() {
        if (serviceBeans.size() > 0) return;
        Api.config(ApiConfig.SERVICE_URL, null).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                ServiceBean serviceBean = new Gson().fromJson(res, ServiceBean.class);
                if (serviceBean != null && serviceBean.getCode() == 200) {
                    serviceBeans = serviceBean.getRows();
                    handler.sendEmptyMessage(0x02);
                }
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }

    //轮播数据
    private void getBannerUrl() {
        if (urls != null && urls.size() != 0) return;
        Api.config(ApiConfig.HOME_BANNER_URL, null).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                HomeBannerBean bannerBean = new Gson().fromJson(res, HomeBannerBean.class);
                if (bannerBean != null && bannerBean.getCode() == 200) {
                    List<HomeBannerBean.RowsBean> beans = bannerBean.getRows();
                    for (int i = 0; i < beans.size(); i++) {
                        urls.add(ApiConfig.BASE_URL + beans.get(i).getAdvImg());
                    }
                    handler.sendEmptyMessage(0x01);
                }
            }

            @Override
            public void onFailure(Exception e) {
            }
        });
    }

    //搜索跳转
    private void toStartSearchResult() {
        //拿到搜索框关键字
        final String key = etSearch.getText().toString();
        //创建搜索结果List
        List<NewsBean.RowsBean> data = new ArrayList<>();
        //遍历当前获取到的新闻数据 因为是根据类型获取新闻数据，一次只获取到一个类型的新闻，这个搜索只是在本地数据当中搜索
        for (NewsBean.RowsBean bean : newsBeans) {
            if (bean.getTitle().contains(key)) data.add(bean);
        }
        //无论有无数据 跳转详情
        Intent intent = new Intent(getActivity(), SearchResultActivity.class);
        intent.putExtra("data", (Serializable) data);
        startActivity(intent);
    }

    @SuppressLint("HandlerLeak")
    class MHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 0x01:
                    banner.setImages(urls);
                    banner.setImageLoader(new ImageLoader() {
                        @Override
                        public void displayImage(Context context, Object o, ImageView imageView) {
                            Glide.with(context).load(o).into(imageView);
                        }
                    });
                    banner.setDelayTime(3000);
                    banner.start();
                    banner.startAutoPlay();
                    break;
                case 0x02:
                    //获取数据后调用 主页服务图标8个 过滤掉第七个之后
                    if (serviceBeans.size() > 8) {
                        List<ServiceBean.RowsBean> data = serviceBeans.subList(0, 7); //左闭右开 0到7 实际是0到6，不包含7
                        //额外添加一个更多服务标签
                        ServiceBean.RowsBean bean = new ServiceBean.RowsBean();
                        bean.setServiceName("更多服务");
                        data.add(bean);
                        recycleAdapter = new ServiceRecycleAdapter(getActivity(), data);
                        setRecycleViewEvent();
                        rvService.setAdapter(recycleAdapter);
                    }
                    break;
                case 0x03:
                    //获取新闻类型后调用 新闻类型tab设置
                    if (dataBeans != null) {
                        for (int i = 0; i < dataBeans.size(); i++) {
                            TabLayout.Tab tab = typeTab.newTab();
                            tab.setText(dataBeans.get(i).getName());
                            typeTab.addTab(tab);
                            newsType.add(dataBeans.get(i).getId());
                        }
                    }
                    //获取新闻类型后立刻加载新闻
                    getNews();
                    break;
                case 0x04:
                    //设置新闻列表
                    //若适配器为null 新建
                    if (newsListAdapter == null) {
                        newsListAdapter = new NewsListAdapter(getActivity(), newsBeans);
                    } else { //若有适配器 重新设置适配器数据
                        newsListAdapter.setNewsBeans(newsBeans);
                    }
                    lvNews.setAdapter(newsListAdapter);
                    break;
                case 0x05:
                    HomeFragment.this.getNews();
                    break;
            }
        }
    }

}